import { register, refresh } from "@/api";
import { focus, unfocus, changePass } from '@/api/user';
import { add_article, comment } from '@/api/article';
import md5 from 'md5';
/**
 * 判断是不是一个数组
 * @param {*} arr 
 */
export const isArray = (arr) => {
    if (Array.isArray) {
        return Array.isArray(arr);
    } else {
        return Object.prototype.toString.call(arr) === '[object Array]';
    }
}


export function parse(val) {
    return JSON.parse(val);
}

export function stringify(val) {
    return JSON.stringify(val);
}

/**
 * 获取过去时间到现在时间的距离
 * @param {*} oldTime 
 */
export const getDiffHistory = (oldTime) => {
    let formats = {
        'year': '几 年前',
        'month': '几 月前',
        'day': '几 天前',
        'hour': '几 小时前',
        'minute': '几 分钟前',
        'second': '几 秒前',
    };
    //获取当前时间戳
    let now = Date.now();
    let seconds = Math.floor((now - parseInt(oldTime)) / 1000);
    let minutes = Math.floor(seconds / 60);
    let hours = Math.floor(minutes / 60);
    let days = Math.floor(hours / 24);
    let months = Math.floor(days / 30);
    let years = Math.floor(months / 12);
    let oldType = '';
    let oldValue = 0;
    if (years > 0) {
        //几年前
        oldType = 'year';
        oldValue = years;
    } else {
        if (months > 0) {
            //几个月前
            oldType = 'month';
            oldValue = months;
        } else {
            if (days > 0) {
                //几天前
                oldType = 'day';
                oldValue = days;
            } else {
                if (hours > 0) {
                    //几小时前
                    oldType = 'hour';
                    oldValue = hours;
                } else {
                    //这里  您可以处理一个  刚刚  比如时间小于30分钟
                    if (minutes > 0) {
                        //几分钟前   
                        oldType = 'minute';
                        oldValue = minutes;
                    } else {
                        //几秒前 
                        oldType = 'second';
                        oldValue = seconds === 0 ? (seconds = 1) : seconds;
                    }
                }
            }
        }
    }
    return formats[oldType].replace('几', oldValue);
}




/**
 * 处理文章数据
 * @param {*} data 
 */
export const normlizeArticleMsg = (data) => {
    if (isArray(data)) {
        return data.map(item => {
            const { title, author, createdAt, _id, agree, agreeUsers, sort, tag, article_img, article } = item;
            return {
                author: author.username,
                title,
                agree,
                historyTime: getDiffHistory(new Date(createdAt).getTime()), // 获取到现在的时间的差
                id: _id,
                userId: author._id,
                agreeUsers,
                sort,
                tag,
                article,
                article_img,
                currentUserId: getUserInfoFromSession() && getUserInfoFromSession()._id
            }
        })
    }
}


/**
 * 根据时间获取年月日
 * @param {*} time 
 */
export const getTimeMsg = (time) => {
    const date = new Date(time)
    const month = date.getMonth() < 10 ? "0" + date.getMonth() : date.getMonth();
    const day = date.getDate() < 10 ? "0" + date.getDate() : date.getDate();
    return date.getFullYear() + '-' + month + '-' + day;
}

/**
 * 处理单篇文章
 * @param {*} data 
 */
export const normlizeArticle = (data) => {
    const header = {};
    const article = {};
    header.author = data.author.username;
    header.time = getTimeMsg(data.createdAt);
    header.view = data.view;
    header.avatar = data.author.avatar
    header.id = data.author._id;
    article.title = data.title;
    article.article_html = data.article_html;
    return {
        header,
        article
    }
}

/**
 * 存入session
 * @param {*} key 
 * @param {*} val 
 */
export function setSessionStorage(key, val) {
    sessionStorage.setItem(key, val);
}

/**
 * 获取session中的key的值
 * @param {*} key 
 */
export function getSessionStorage(key) {
    return sessionStorage.getItem(key);
}


export const clearSessionStorage = (key) => {
    sessionStorage.removeItem(key);
}

/**
 *将用户信息存入到session中
 * @param {*} info 
 */
export const setUserInfoToSession = (info) => {
    setSessionStorage('userInfo', stringify(info));
}

/**
 * 从session中获取用户信息
 */
export const getUserInfoFromSession = () => {
    const user = getSessionStorage('userInfo');
    if (user) {
        return parse(user);
    }
    return null;
}

/**
 * 弹窗显示消息
 * @param {*} instance 
 * @param {*} msg 
 */
export function success(instance, msg) {
    instance.$message.success(msg);
}
/**
 * 弹窗显示消息
 * @param {*} instance 
 * @param {*} msg 
 */
export function error(instance, msg) {
    instance.$message.error(msg);
}

/**
 * 登录
 * @param {*} userInfo 
 * @param {*} instance 
 */
export async function handleLogin(userInfo, instance) {
    instance.$store.dispatch('login', { data: { ...userInfo, password: md5(userInfo.password) }, instance })
}

/**
 * 注册
 * @param {*} userInfo 
 * @param {*} instance 
 */
export async function handleRegister(userInfo, instance) {
    const result = await register({
        data: { ...userInfo, password: md5(userInfo.password) },
    });
    if (result.code == 1) {
        instance.$emit('changeLogin', true);
        // 将表单清空
        instance.formInline.username = '';
        instance.formInline.password = '';
        instance.formInline.repassword = '';
        success(instance, result.msg);
    } else {
        error(instance, result.msg);
    }
}

/**
 * 退出登录
 *  @param {*} instance 
 */
export async function handleLogOut(instance) {
    instance.$store.dispatch('logout', instance);
}


/**
 * 刷新登录
 */
export const refreshPage = async () => {
    return await refresh()
}

export const handleTest = async () => {
    return await test();
}


/**
 * 发布文章
 * @param {*} instance 
 */
export const postArticle = async (instance) => {
    const { title, article, tag, sort } = instance;
    let imgTag = `<div class="wrap-img fx-c">
    <img src="${instance.article_img}" style='width: 652px; margin: 1rem 0; object-fit: cover;' alt="" />
</div>`
    const article_html = imgTag + instance.article_html;
    if (title && article && tag && sort) {
        const data = { title, article, article_html, sort, tag, article_img: instance.article_img };
        // 发布文章
        const r = await add_article({
            data,
        });
        if (r.code == 1) {
            // 发布文章成功要置空
            instance.title = "";
            instance.$bus.$emit("resetToEmpty");
            // 清除原来没有登录保存的文章信息
            clearSessionStorage('tempArticleMsg');
            instance.$message.success(r.msg + "即将返回首页", 0.5);

            // 将弹窗tag & sort清除
            instance.$bus.$emit("emitVisible", false);
            setTimeout(() => {
                instance.$router.push("/"); // 返回主页
            }, 1000);
        } else {
            instance.$message.error(r.msg + ", 请返回返回首页进行登录", 0.5);
            setSessionStorage("tempArticleMsg", stringify(data));
            setTimeout(() => {
                instance.$router.push({ path: "/", query: { from: instance.$route.path } }); // 返回主页
            }, 1000);
        }
    } else if (!title) {
        instance.$message.warn('请您填写标题!', 0.5);
    } else if (!article) {
        instance.$message.warn('请您填写文章', 0.5);
    } else if (!tag) {
        instance.$message.warn('请您填写标签', 0.5);
    } else if (!sort) {
        instance.$message.warn('请您填写好分类', 0.5);
    }
}


/**
 * 处理用的数据动态
 * @param {*} data 
 */
export const normlizeUseDynic = (data, user) => {
    if (isArray(data)) {
        const arr = [];
        data.forEach(item => {
            switch (item.code) {
                case 5:
                case 1:
                    const { time, article, userId } = item;
                    const { _id, title, article: art, agreeUsers, agree } = article;
                    arr.push({
                        header: {
                            time: getDiffHistory(time),
                            articleId: _id
                        },
                        body: {
                            title: title,
                            article: art.substr(0, 98) + '...',
                            id: _id
                        },
                        aboutArt: {
                            agree: agree,
                            agreeUsers: agreeUsers,
                            userId,
                            artId: _id
                        },
                        code: item.code,
                        rawTime: item.time
                    })
                case 2:
                    break;
                case 3:
                    const { focusUserName, time: tTime } = item;
                    arr.push({
                        username: user.username,
                        focusUserName: focusUserName,
                        avatar: user.avatar,
                        job: user.job,
                        time: tTime,
                        rawTime: tTime
                    })
                    break;
                case 4:
                    break;

            }
        })
        arr.sort((a, b) => b.rawTime - a.rawTime)
        return arr;
    } else {
        return {}
    }
}

/**
 * 格式化关注用户的数据
 * @param {*} data 
 */
export const normlizeFocusUsers = (data) => {
    if (isArray(data)) {
        return data.map(item => {
            const obj = {}
            const { avatar, username, _id, job } = item.data;
            obj.avatar = avatar;
            obj.username = username;
            obj.id = _id;
            obj.job = job;
            return obj;
        })
    }
    return [];
}

export const handleFocus = async (id, instance) => {
    const currentUserInfo = getUserInfoFromSession();
    if (!instance.isFocus) {
        // 关注
        if (currentUserInfo) {
            const currentUserId = currentUserInfo._id;
            // 当前用户和文章一样，不能关注
            if (id === currentUserId) {
                instance.$message.warn("id一样，不能自己关注自己");
                return;
            }
        }
        const result = await focus(id);
        if (result.code == 1) {
            instance.foc = true;

            // 更改store中的用户信息
            instance.$store.commit("userData", result.data);
            instance.$message.success("关注成功!!");
        } else {
            instance.$message.error("关注失败");
        }
    } else {
        // 已关注，现在要取消关注
        if (currentUserInfo) {
            const currentUserId = currentUserInfo._id;
            // 当前用户和文章一样，不能关注
            if (id === currentUserId) {
                instance.$message.warn("id一样，不能自己取消关注自己");
                return;
            }
        }
        const result = await unfocus(id);
        if (result.code == 1) {
            instance.foc = false;

            // 更改store中的用户信息
            instance.$store.commit("userData", result.data);
            instance.$message.success("取消关注成功!!");
        } else {
            instance.$message.error("取消关注失败");
        }
    }
}


export const changePassWord = async (password, repassword, instance) => {
    const r = await changePass(password, repassword);
    if (r.code == 1) {
        instance.$message.success(r.msg + ",请重新登录");
        instance.formInline.password = '';
        instance.formInline.repassword = '';
        // 隐藏弹窗
        instance.$emit('changeVisible', false);
        // 退出登录
        instance.$store.dispatch('logout', { instance, noAlert: true });
    } else {
        instance.$message.error(r.msg);
    }
}


/**
 * 处理搜索文章的结果
 * @param {*} data 
 */
export const normlizeArticleMsgAndAddColor = (data, q) => {
    const r = normlizeArticleMsg(data);
    r.forEach(item => {
        for (let prop in item) {
            markWord(prop, item, q)
        }
    })
    return r;
}

/**
 * 处理搜索的用户
 * @param {*} data 
 * @param {*} q 
 */
export const normliszeUser = (data, q) => {
    if (!isArray(data)) return []
    return data.map(item => {
        return {
            avatar: item.avatar,
            job: item.job,
            id: item._id,
            username: item.username.replace(q, `<mark index="0" text="${q}" class="text__highlight" style="background-color: rgb(255, 255, 255); color: rgb(240, 53, 53);">${q}</mark>`),
            focusNums: item.follows.length
        }
    })
}

/**
 * 处理综合搜索结果
 * @param {*} data 
 * @param {*} q 
 */
export const normliszeAll = (data, q) => {
    if (!isArray(data)) return []
    let ret = []
    data.forEach(item => {
        let r;
        if (item.article) {
            r = normlizeArticleMsgAndAddColor(item.r1, q)
        } else {
            r = normliszeUser(item.r2, q)
        }
        ret = ret.concat(r);
    })
    return ret;
}

/**
 * 发送评论
 * @param {*} articleId 
 * @param {*} content 
 * @param {*} imgUrl 
 * @param {*} commentUserId 
 * @param {*} instance 
 */
export const resolveComment = (articleId, content, imgUrl, commentUserId, instance) => {
    if (content) {
        content = `<div class='fx-h-c'>${content}</div>`
    }
    if (imgUrl) {
        content += `<div>
          <img style='width: 8rem; height: 8rem; margin-top: 1rem' src="${imgUrl}" alt="" />
        </div>`;
        if (!commentUserId) return instance.$message.error("请先登录再评论");
    }
    const r = comment({
        articleId,
        content,
        commentUserId
    });
    return r;
}

/**
 * 处理评论
 * @param {*} data 
 */
export const normlizeComment = (data) => {
    const comments = data.comments;
    if (isArray(comments)) {
        return comments.map(item => {
            const { time, commentUser, content, articleId, commentUserId } = item;
            return {
                content,
                avatar: commentUser.avatar,
                username: commentUser.username,
                job: commentUser.job,
                commentUserId,
                commentCount: commentUser.length,
                articleId,
                rawTime: time,
                time: getDiffHistory(item.time || Date.now())
            }
        })
    }
}

export const normlizeUserMsg = (data) => {
    if (isArray(data)) {
        let agree = 0,
            view = 0;
        data.forEach(item => {
            agree += item.agree;
            view += item.view;
        })
        return {
            agree,
            view
        }
    }
}


/**
 * 标记关键字
 */
function markWord(prop, item, q) {
    if (prop == 'title' || prop === 'article') {
        if (item[prop].includes(q)) {
            item[prop] = item[prop].replace(q, `<mark index="0" text="${q}" class="text__highlight" style="background-color: rgb(255, 255, 255); color: rgb(240, 53, 53);">${q}</mark>`)
        }
    }
}